var dlTabsBrowserOverlay = {

	init: function(e)
	{
		if(!this.initialized)
		{
			this.initialized = true;
			
			// Don't show Firefox's monitor in the status bar
			document.getElementById("download-monitor").collapsed = true;
			
			// tab table only used for managing tabs that will automatically close
			this.tabTable = new Array();
			
			/* Because I can't mess with the tab context menu on a per-tab basis,
			 * I have to change it here
			 */
			this.tabContextMenu = gBrowser.mStrip.getElementsByAttribute("anonid", "tabContextMenu")[0];
			
			// Locales
			this.strbundle = document.getElementById("strings");
			
			var menus = document.getElementById("dlTabs_tabMenu");
			while(menus.childNodes.length > 0)
			{
				this.tabContextMenu.appendChild(menus.childNodes[0]);
			}
			
			// Change the callbacks
			this.tabContextMenu.setAttribute("onpopupshowing", 
							"document.popupNode.getAttribute(\"dlTabsTab\") "
							+ "? dlTabsBrowserOverlay.shiftContextMenu() "
							+ ": dlTabsBrowserOverlay.unshiftContextMenu();");

			// Eventually I will add locales
			this.strings = document.getElementById("downloadtabs-strings");
			
			dlTabsPrefs.init();
			
			// Add the listener for new downloads
			this.dm = Components.classes["@mozilla.org/download-manager;1"]
							.getService(Components.interfaces.nsIDownloadManager);
			this.dm.addListener(this);
			
			// Check there actually is a sidebar
			this.checkSidebarAvailibility();
			
			// Preload images
			this.preload();
			
			
		}
	},
	
	preload : function()
	{
		var extDir = getExtensionPath();
		var skinDir = Components.classes["@mozilla.org/file/local;1"]
                    .createInstance(Components.interfaces.nsILocalFile);
		skinDir.initWithPath(extDir.path + "\\chrome\\skin\\default");
		consoleLog("directory: " + skinDir.path);
		if(skinDir.isDirectory())
		{
			var entries = skinDir.directoryEntries;
			while(entries.hasMoreElements())  
			{  
				var entry = entries.getNext();  
				entry.QueryInterface(Components.interfaces.nsIFile);
				if(entry.leafName.indexOf(".png") != -1)
					preloadImage("chrome://downloadtabs/skin/" + entry.leafName);
			} 
		}
	},
	
	checkSidebarAvailibility : function()
	{
		if(document.getElementById("sidebar-box"))
		{
			consoleLog("Sidebar present: Tab Kit");
			return(true);
		}
	},
	
	getPopupDownload : function()
	{
		var target = document.popupNode;
		var download;
		try
		{
			var id = target.getAttribute("dlTabsTab_dl");
			download = this.dm.getDownload(id);
		}
		catch(exception)
		{
			download = 0;
		}
		return(download);
	},
	
	// Change the tab context menu to the DownloadTabs context menu
	shiftContextMenu : function()
	{
		// Change the labels to match the target download
		var dl = this.getPopupDownload();
		if(dl)
		{
			setLabels(dl.state, document.getElementById("pauseMenu"),
								document.getElementById("cancelMenu"), 
								document.getElementById("launchMenu"),
								this.strbundle);
			// Re-enable in case it was disabled
			document.getElementById("removeMenu").setAttribute("disabled", "false");
			document.getElementById("deleteMenu").setAttribute("disabled", "false");
			document.getElementById("copyMenu").setAttribute("disabled", "false");
			document.getElementById("openMenu").setAttribute("disabled", "false");
		}
		else
		{
			disableLabels(document.getElementById("pauseMenu"),
								document.getElementById("cancelMenu"), 
								document.getElementById("launchMenu"),
								this.strbundle);
			// Disable the other context menus
			document.getElementById("removeMenu").setAttribute("disabled", "true");
			document.getElementById("deleteMenu").setAttribute("disabled", "true");
			document.getElementById("copyMenu").setAttribute("disabled", "true");
			document.getElementById("openMenu").setAttribute("disabled", "true");
		}
		
		// Hide the non-dlTabs menus and display dlTabs menus
		var item = this.tabContextMenu.firstChild;
		while(item)
		{
			if(!item.getAttribute("downloadtabs"))
				item.style.setProperty("display", "none", "important");
			else
				item.style.setProperty("display", "", "important");
			item = item.nextSibling;
		}
		return(true);
	},
	
	// Change the tab context menu back to the normal context menu
	unshiftContextMenu : function()
	{
		var target = document.popupNode;
		var item = this.tabContextMenu.firstChild;
		while(item)
		{
			if(!item.getAttribute("downloadtabs"))
				item.style.setProperty("display", "", "important");
			else
				item.style.setProperty("display", "none", "important");
			item = item.nextSibling;
		}
		
		// The default action
		return(this.parentNode.parentNode.parentNode.updatePopupMenu(this));
	},
	
	onDownloadStateChange : function(state, dl)
	{
		var id = dl.id;
		
		// New download? (Was queued, state now changed)
		if(state == Components.interfaces.nsIDownloadManager.DOWNLOAD_QUEUED)
		{
			if(dlTabsPrefs.getAutoOpen() == "each")
			{
				var time = dlTabsPrefs.match(dl);
				if(time != -1)
				{
					var tab = gBrowser.addTab("chrome://downloadtabs/content/tab.xul?id=" + id);
					
					
					tab.setAttribute("dlTabsTab_closeTime", time);
				}
			}
			else if(dlTabsPrefs.getAutoOpen() == "all")
			{
				// TODO implement
			}
		}
    },
	
	onSecurityChange : function(prog, req, state, dl)
	{
    },
	
    onProgressChange : function(prog, req, prog, progMax, tProg, tProgMax, dl)
	{
    },
	
    onStateChange : function(prog, req, flags, status, dl)
	{
    },
	
	// -----Utility-----
	
	sendEvent : function(event, tab)
	{
		var newEvt = document.createEvent("MessageEvent");
		newEvt.initMessageEvent("dlTabs_" + event, false, true,
								event,
								window.location.protocol + "//" + window.location.host,
								12, window);
		tab.dispatchEvent(newEvt);
	},
	
	// -----Callbacks---
	
	pause : function()
	{
		pauseDownload(this.getPopupDownload(), this.dm);
	},
	
	cancel : function()
	{
		cancelDownload(this.getPopupDownload(), this.dm);
	},
	
	remove : function()
	{
		removeDownload(this.getPopupDownload(), this.dm);
		this.sendEvent("close", document.popupNode);
	},
	
	deleteDownload : function()
	{
		deleteDownload(this.getPopupDownload(), this.dm);
		this.sendEvent("close", document.popupNode);
	},
	
	openFolder : function()
	{
		openDownloadFolder(this.getPopupDownload());
	},
	
	copyDownloadLink : function()
	{
		copyDownload(this.getPopupDownload());
	},
	
	launch : function()
	{
		this.sendEvent("launch", document.popupNode);
	}
};

window.addEventListener("load", 
	function(e)
	{
		dlTabsBrowserOverlay.init(e);
	},
	false);